import { Injectable } from '@nestjs/common';
import { EntityManager } from 'typeorm';
import { UniqueCodeService } from './unique-code.service';
import { ShortLongMap } from './entity/ShortLongMap';
import { UniqueCode } from './entity/uniqueCode';

@Injectable()
export class ShortLongMapService {
  constructor(
    private readonly entityManager: EntityManager,
    private readonly uniqueCodeService: UniqueCodeService,
  ) {}

  async generate(longUrl: string) {
    let uniqueCode = await this.entityManager.findOneBy(UniqueCode, {
      status: 0,
    });

    if (!uniqueCode) {
      uniqueCode = await this.uniqueCodeService.generateCode();
    }

    await this.entityManager.save(ShortLongMap, {
      shortUrl: uniqueCode.code,
      longUrl,
    });

    await this.entityManager.update(UniqueCode, uniqueCode.id, {
      status: 1,
    });

    return uniqueCode.code;
  }

  async getLongUrl(shortUrl: string) {
    const shortLongMap = await this.entityManager.findOneBy(ShortLongMap, {
      shortUrl,
    });

    return shortLongMap?.longUrl;
  }
}
